//导入express
const express = require('express')

//创建服务器对象
const app = express()
const joi = require('joi')

//导入配置cors中间件
const cors = require('cors')
app.use(cors())

//配置解析表单数据的中间件
//注意：只能配置解析 application/x-www-form-urlencoded 格式的表单数据
app.use(express.urlencoded({ extended: false }))

//托管静态资源
app.use('/uploads', express.static('./uploads'))

//要在路由之前定义封装的res.cc()函数
app.use((req, res, next) => {
  // 默认为一表示失败情况
  res.cc = (err, status = 1) => {
    res.send({
      status,
      message: err instanceof Error ? err.message : err
    })
  }
  next()
})

//导入配置Token中间件
const config = require('./schema/config.js')
const expressJWT = require('express-jwt')
//配置全局中间件
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api/] }))

//导入使用用户模块
const userRouter = require('./router/user.js')
app.use('/api', userRouter)
//导入用户基本信息的模块
const userInfoRouter = require('./router/userinfo')
app.use('/my', userInfoRouter)
//导入文章分类的模块
const artCateRouter = require('./router/artcate')
app.use('/my/article', artCateRouter)
//导入文章模块
const articleRorter = require('./router/article')
app.use('/my/article', articleRorter)

//定义错误级别中间件
app.use((err, req, res, next) => {
  //验证失败导致的错误
  if (err instanceof joi.ValidationError) return res.cc(err)
  //身份认证失败
  if (err.name === 'UnauthorizedError') return res.cc('身份认证失败！')
  //未知的错误
  res.cc(err)
})

//启动服务器
app.listen(3007, () => {
  console.log('server  running at http://127.0.0.1:3007')
})
